package stu

import (
	"log"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

const BaseURL = "https://stu.5zk.com.cn/zk8exam/"

type StuCourse struct {
	ID        string `json:"id,omitempty"`
	Path      string `json:"path,omitempty"`
	Name      string `json:"name,omitempty"`
	TotalTime int    `json:"total_time,omitempty"`
	Completed bool   `json:"completed,omitempty"`
}

// 提取课程信息
func extractCourseInfo(document *goquery.Document) (string, int, int, bool) {
	jjwikiid, _ := document.Find("#jjwikiid").Attr("value")
	cur_jindu, _ := document.Find("#cur_jindu_old").Attr("value")
	shichang, _ := document.Find("#shichang").Attr("value")

	re := regexp.MustCompile(`\d+(\.\d+)?`) // 匹配整数或浮动小数

	cur_jindu = re.FindString(cur_jindu)
	currTime, _ := strconv.Atoi(cur_jindu)
	shichang = re.FindString(shichang)
	totalTime, _ := strconv.Atoi(shichang)

	completed := currTime >= totalTime
	return jjwikiid, totalTime, currTime, completed
}

// 获取页面课程列表（直播）
func FetchPageListLive(client *http.Client, pageURL string) (map[string]StuCourse, error) {
	courseMap := make(map[string]StuCourse)

	resp, err := client.Get(pageURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	document, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}

	courseList := []string{}
	document.Find("td a.btn.btn-primary.mr-5.mb-5").Each(func(index int, item *goquery.Selection) {
		courUrl := BaseURL + item.AttrOr("href", "")
		courseList = append(courseList, courUrl)
	})

	// 获取每个课程详细信息
	for _, courseUrl := range courseList {
		resp, err := client.Get(courseUrl)
		if err != nil {
			continue
		}
		defer resp.Body.Close()

		document, err := goquery.NewDocumentFromReader(resp.Body)
		if err != nil {
			log.Println("Error parsing course document:", err)
			continue
		}

		jjwikiid, totalTime, _, completed := extractCourseInfo(document)

		courseMap[jjwikiid] = StuCourse{
			Path:      courseUrl,
			ID:        jjwikiid,
			TotalTime: totalTime,
			Completed: completed,
		}
	}
	return courseMap, nil
}

// 获取页面课程列表（非直播）
func FetchPageListNonLive(client *http.Client, pageURL string) (map[string]StuCourse, error) {
	courseMap := make(map[string]StuCourse)

	resp, err := client.Get(pageURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	document, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}

	document.Find("li div.font-w200").Each(func(index int, item *goquery.Selection) {
		sibling := item.Next()
		text := sibling.Text()
		re := regexp.MustCompile(`\((\d{2}:\d{2}:\d{2})/(\d{2}:\d{2}:\d{2})\)`)
		match := re.FindStringSubmatch(text)

		var totalLength, currentTime int
		if len(match) > 1 {
			currentTime = timeToSeconds(match[1])
			totalLength = timeToSeconds(match[2])
		}

		item.Find("a").Each(func(aIndex int, aItem *goquery.Selection) {
			coursePath, hrefExists := aItem.Attr("href")
			if !hrefExists {
				return
			}

			parsedURL, err := url.Parse(coursePath)
			if err != nil {
				return
			}

			queryParams := parsedURL.Query()
			jjwikiid := queryParams.Get("jjwikiid")
			if jjwikiid == "" {
				return
			}

			completed := totalLength == 0 || currentTime >= totalLength
			courseMap[jjwikiid] = StuCourse{
				Path:      BaseURL + coursePath,
				ID:        jjwikiid,
				TotalTime: totalLength,
				Completed: completed,
			}
		})
	})

	return courseMap, nil
}

/**
 * 将时间字符串转换为秒数
 * @param timeStr 时间字符串，格式为 "HH:MM:SS"
 */
func timeToSeconds(timeStr string) int {
	parts := strings.Split(timeStr, ":")
	if len(parts) != 3 {
		return 0
	}
	hours, _ := strconv.Atoi(parts[0])
	minutes, _ := strconv.Atoi(parts[1])
	seconds, _ := strconv.Atoi(parts[2])
	return hours*3600 + minutes*60 + seconds
}
